<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2017/12/24
 * Time: 下午6:53
 */

namespace Biz\module\Classes;

use Biz\model\OperateLog as mOperateLog;
use Biz\model\ShopAuth;
use Biz\model\ShopBasicInfo as mShopBasicInfo;
use Biz\model\ShopCompanyInfo as mShopCompanyInfo;
use Biz\model\ShopPersonalInfo as mShopPersonalInfo;
use Biz\model\ShopSecurityDeposit as mShopSecurityDeposit;
use Biz\module\Classes\core\StatusAbstract;
use Biz\service\MessageSend;
use Biz\service\MessageSend as sMessageSend;
use Biz\service\OperateLog as sOperateLog;
use Biz\service\ShopCommissionRate;
use Biz\service\ShopSecurityDeposit as sShopSecurityDeposit;
use Biz\pockets\serviceTrait\_Async;
use Doraemon\tools\Sms as tSms;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\service\SmallEnergy as sSmallEnergy;


final class ShopStatus extends StatusAbstract
{
    use _Async;
    //操作列表常量
    const ACTION_ADMIN_DEPOSIT = 'adminDeposit';
    const ACTION_REJECT_APPLY = 'rejectApply';
    const ACTION_COMPLETE_APPLY = 'completeApply';
    const ACTION_CONFIRM_OPENDED = 'confirmOpened';
    const ACTION_CONFIRM_CLOSE = 'confirmClose';
    const ACTION_CONFIRM_FROZEN = 'confirmFrozen';
    const ACTION_CANCEL_FROZEN = 'cancelFrozen';

    protected static $actionsDesc = [
        self::ACTION_ADMIN_DEPOSIT => '管理保证金',
        self::ACTION_REJECT_APPLY => '驳回申请',
        self::ACTION_COMPLETE_APPLY => '资料通过',
        self::ACTION_CONFIRM_OPENDED => '确认开店',
        self::ACTION_CONFIRM_CLOSE => '关店',
        self::ACTION_CONFIRM_FROZEN => '冻结',
        self::ACTION_CANCEL_FROZEN => '解冻',
    ];

    protected static $actionsAdminUrl = [
        'adminDeposit' => 'admin/shop/deposit/manage',
        'rejectApply' => 'admin/shop/ctrl/shop/status/' . mShopBasicInfo::STATUS_REJECT,
        'completeApply' => 'admin/shop/ctrl/shop/status/' . mShopBasicInfo::STATUS_WAIT_PAY_DEPOSIT,
        'confirmOpened' => 'admin/shop/ctrl/shop/status/' . mShopBasicInfo::STATUS_OPENED,
        'confirmClose' => 'admin/shop/ctrl/shop/status/' . mShopBasicInfo::STATUS_CLOSED,
        'confirmFrozen' => 'admin/shop/ctrl/shop/status/' . mShopBasicInfo::STATUS_FROZEN,
        'cancelFrozen' => 'admin/shop/ctrl/shop/status/' . mShopBasicInfo::STATUS_OPENED,
    ];

    protected static $statusAdminActionsMap = [
        mShopBasicInfo::STATUS_REJECT => [self::ACTION_ADMIN_DEPOSIT],
        mShopBasicInfo::STATUS_WAIT_PAY_DEPOSIT => [self::ACTION_ADMIN_DEPOSIT, self::ACTION_CONFIRM_OPENDED],
        mShopBasicInfo::STATUS_WAIT_AUDIT => [self::ACTION_ADMIN_DEPOSIT, self::ACTION_REJECT_APPLY, self::ACTION_COMPLETE_APPLY],
        mShopBasicInfo::STATUS_OPENED => [self::ACTION_ADMIN_DEPOSIT, self::ACTION_CONFIRM_FROZEN],
        mShopBasicInfo::STATUS_FROZEN => [self::ACTION_CANCEL_FROZEN, self::ACTION_CONFIRM_CLOSE],
    ];


    public static function rejectApply($uid, $shopType, $remark, $oldStatus, $adminUid)
    {
        try {

            $ret = mShopBasicInfo::action(function () use ($uid, $shopType, $remark) {
                $data = mShopBasicInfo::update(['status' => mShopBasicInfo::STATUS_REJECT], ['uid' => $uid]);

                if ($data->rowCount() == 0) {
                    throw new \Exception('状态修改失败');
                }

                if ($shopType == mShopBasicInfo::TYPE_COMPANY) {
                    mShopCompanyInfo::createOrEdit($uid, ['remark' => $remark], 'manage');
                } elseif ($shopType == mShopBasicInfo::TYPE_PERSONAL) {
                    mShopPersonalInfo::createOrEdit($uid, ['remark' => $remark], 'manage');
                }
            });

            if ($ret !== false) {


                sMessageSend::sendShopEmailByUid($uid, 'shop_reject_apply',
                    ['reason' => $remark, 'sign_link' => 'https://seller.haohaozhu.com/#/user/login']);

                sMessageSend::sendShopSmsByUid($uid, tSms::TYPE_SHOP_REJECT_APPLY, ['reason' => $remark]);


                sOperateLog::record(mOperateLog::TYPE_SHOP_ADM_CHANGE_STATUS, 0, $uid, ['uid' => $uid, 'old_status' => $oldStatus], ['new_status' => mShopBasicInfo::STATUS_REJECT], $adminUid);

            }


        } catch (\Exception $e) {
            throw $e;
        }
    }

    public static function mgtSubmitWaitAudit($uid)
    {
        try {
            $info = mShopBasicInfo::getInfo($uid);

            if (!in_array($info['status'], [mShopBasicInfo::STATUS_NORMAL, mShopBasicInfo::STATUS_REJECT])) {
                throw new \Exception('请从正确渠道提交审核');
            }

            $ret = mShopBasicInfo::action(function () use ($uid) {
                $data = mShopBasicInfo::update(['status' => mShopBasicInfo::STATUS_WAIT_AUDIT], ['uid' => $uid]);

                if ($data->rowCount() == 0) {
                    throw new \Exception('状态修改失败');
                }
            });

        } catch (\Exception $e) {
            throw $e;
        }
    }

    public static function confirmOpened($uid, $shopType, $remark, $oldStatus, $adminUid)
    {
        try {
            $info = mShopBasicInfo::getInfo($uid);

            $ret = mShopBasicInfo::action(function () use ($uid) {

                $info = mShopSecurityDeposit::getInfo($uid);

                if ($info['balance'] < $info['amount']) {
                    throw new \Exception('保证金余额不足，不能开店');
                }

                $data = mShopBasicInfo::update(['status' => mShopBasicInfo::STATUS_OPENED], ['uid' => $uid]);


                if ($data->rowCount() == 0) {
                    throw new \Exception('状态修改失败');
                }

            });

            sMessageSend::sendShopEmailByUid($uid, 'confirm_opened_shop', ['shop_name' => $info['name']]);

            sMessageSend::sendShopSmsByUid($uid, tSms::TYPE_SHOP_OPEND_SUCCESS);

            sOperateLog::record(mOperateLog::TYPE_SHOP_ADM_CONFIRMED_SHOP_OPEND, 0, $uid, ['uid' => $uid, 'old_status' => $oldStatus], ['new_status' => mShopBasicInfo::STATUS_OPENED], $adminUid);


        } catch (\Exception $e) {
            throw $e;
        }
    }


    /**
     * 资料通过
     * @param $uid
     * @param $shopType
     * @param $remark
     * @param $amount
     * @param $definedRatio
     * @param $categoryRatio
     * @throws \Exception
     */
    public static function completeApply($uid, $adminUid, $amount, $definedRatio, $categoryRatio)
    {
        try {


            //更新保证金及保证金状态
            sShopSecurityDeposit::admUpdateDepositAmount($uid, $adminUid, $amount, mShopSecurityDeposit::STATUS_NOT_PAY);

            //设置默认佣金
            ShopCommissionRate::setDefinedRatio($uid, $definedRatio);
            //设置经营类目及佣金
            ShopCommissionRate::setRatios($uid, $categoryRatio, $definedRatio);

            $data = mShopBasicInfo::update(['status' => mShopBasicInfo::STATUS_WAIT_PAY_DEPOSIT], ['uid' => $uid]);
            if ($data->rowCount() == 0) {
                throw new \Exception('状态修改失败');
            }


            //发邮件
            $email = ShopAuth::getEmailByUid($uid);
            self::sendEmail($email, 'shop_complete_apply', ['amount' => $amount]);

        } catch (\Exception $e) {
            throw $e;
        }
    }

    public static function confirmClose($uid, $shopType, $remark, $oldStatus, $adminUid)
    {
        try {

            $ret = mShopBasicInfo::action(function () use ($uid) {


                $data = mShopBasicInfo::update(['status' => mShopBasicInfo::STATUS_CLOSED], ['uid' => $uid]);


                if ($data->rowCount() == 0) {
                    throw new \Exception('状态修改失败');
                }

            });

            sOperateLog::record(mOperateLog::TYPE_SHOP_ADM_CONFIRMED_SHOP_CLOSE, $uid, $uid, ['uid' => $uid, 'old_status' => $oldStatus], ['new_status' => mShopBasicInfo::STATUS_CLOSED], $adminUid);
            //删除已下架商品
            mGoodsBasicInfo::updateData(['status' => mGoodsBasicInfo::STATUS_DELETE], ['shop_id' => $uid, 'status' => [mGoodsBasicInfo::STATUS_OFFLINE, mGoodsBasicInfo::STATUS_ADM_OFFLINE]]);
            //删除小能信息
            sSmallEnergy::admDelSmallEnergyByShopId($uid);
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public static function confirmFrozen($uid, $shopType, $remark, $oldStatus, $adminUid)
    {
        try {

            $ret = mShopBasicInfo::action(function () use ($uid) {


                $data = mShopBasicInfo::update(['status' => mShopBasicInfo::STATUS_FROZEN], ['uid' => $uid]);

                if ($data->rowCount() == 0) {
                    throw new \Exception('状态修改失败');
                }

            });

            sOperateLog::record(mOperateLog::TYPE_SHOP_ADM_CONFIRMED_SHOP_FROZEN, $uid, $remark, ['uid' => $uid, 'old_status' => $oldStatus], ['new_status' => mShopBasicInfo::STATUS_FROZEN], $adminUid);
            //下架所有商品
            mGoodsBasicInfo::updateData(['status' => mGoodsBasicInfo::STATUS_OFFLINE], ['shop_id' => $uid, 'status' => [mGoodsBasicInfo::STATUS_ONLINE]]);


        } catch (\Exception $e) {
            throw $e;
        }
    }

    public static function cancelFrozen($uid, $shopType, $remark, $oldStatus, $adminUid)
    {
        try {

            $ret = mShopBasicInfo::action(function () use ($uid) {


                $data = mShopBasicInfo::update(['status' => mShopBasicInfo::STATUS_OPENED], ['uid' => $uid]);


                if ($data->rowCount() == 0) {
                    throw new \Exception('状态修改失败');
                }

            });

            sOperateLog::record(mOperateLog::TYPE_SHOP_ADM_CANCEL_SHOP_FROZEN, $uid, $uid, ['uid' => $uid, 'old_status' => $oldStatus], ['new_status' => mShopBasicInfo::STATUS_OPENED], $adminUid);

        } catch (\Exception $e) {
            throw $e;
        }
    }

    public static function sendEmail($email, $tag, $params)
    {
        self::_async($email, $tag, $params);
    }

    public static function _async_sendEmail($email, $tag, $params)
    {
        MessageSend::sendEmail($email, $tag, $params);
    }

}